{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import numpy as np\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入数据\n",
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义神经网络结构和前向传播"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "L1 = 500\n",
    "#L2 = 100\n",
    "W1 = tf.Variable(tf.truncated_normal([784, L1],stddev=0.01,seed=1))\n",
    "W2 = tf.Variable(tf.truncated_normal([L1,10],stddev=0.01,seed=1))\n",
    "#W3 = tf.Variable(tf.truncated_normal([L2, 10],stddev=np.sqrt(2/L2),seed=1)) \n",
    "\n",
    "b1 = tf.Variable(tf.constant(0.1,shape=[L1]))\n",
    "b2 = tf.Variable(tf.constant(0.1,shape=[10]))\n",
    "#b3 = tf.Variable(tf.truncated_normal([10],stddev=np.sqrt(2/10),seed=1))\n",
    "\n",
    "logit1 = tf.matmul(x, W1) + b1      #不明白这里维数不一致怎么还能加法运算。 python广播机制，了解一下\n",
    "h1 = tf.nn.relu(logit1)\n",
    "#logit2 = tf.matmul(h1, W2) + b2\n",
    "#h2 = tf.sigmoid(logit2)\n",
    "\n",
    "y = tf.matmul(h1, W2) + b2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义损失函数以及反向传播算法\n",
    "反复运行反向传播优化算法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))#+ tf.contrib.layers.l2_regularizer(0.1)(W1) + tf.contrib.layers.l2_regularizer(0.1)(W2) \n",
    "     #reduce_mean（）就是求输入张量某一维度上的均值，这里求每个batch的均值\n",
    "l2_loss = tf.nn.l2_loss(W1) + tf.nn.l2_loss(W2)    # tf.nn.l2_loss:sum(t ** 2) / 2\n",
    "total_loss = cross_entropy + 0.0001*l2_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "global_step = tf.Variable(0)\n",
    "\n",
    "#通过exponential_decay函数生成学习率\n",
    "learning_rate = tf.train.exponential_decay(0.8,global_step,600,0.89,staircase=True)\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss,global_step=global_step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成会话并训练数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9016\n",
      "0.9353\n",
      "0.9496\n",
      "0.9505\n",
      "0.9512\n",
      "0.9608\n",
      "0.9679\n",
      "0.9707\n",
      "0.9698\n",
      "0.9667\n",
      "0.971\n",
      "0.9727\n",
      "0.9726\n",
      "0.9721\n",
      "0.9758\n",
      "0.9779\n",
      "0.976\n",
      "0.978\n",
      "0.9793\n",
      "0.9789\n",
      "0.9756\n",
      "0.9775\n",
      "0.9791\n",
      "0.9791\n",
      "0.98\n",
      "0.9802\n",
      "0.981\n",
      "0.9797\n",
      "0.9809\n",
      "0.9816\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for i in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    #没100次输出一次准确率\n",
    "    if (i+1)%100 == 0:\n",
    "  # Test trained model          由于softmax不会改变输入的相对大小关系，所以下面的tf.argmax（）中的参数不一定要是经过激活函数后输出的值\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  #tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素，如果是相等的那就返回True，不等返回False\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))    # tf.cast()为类型转换函数，这里讲布尔型转换为浮点数型\n",
    "        \n",
    "       # print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "       #         (i+1, loss, l2_loss_value, total_loss_value))\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率    tf.argmax()中axis参数为0：按行查找；1：按列查找。得到最大值的下标"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
